<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset = "UTF-8">
    <script src="{{url_for('static',filename='js/jquery.min.js')}}"></script>
    <script src="{{url_for('static',filename='js/clientManage.js')}}?{{version}}"></script>
    <script src="{{url_for('static',filename='js/bootstrap.min.js')}}"></script>
    <script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
    <link rel="stylesheet" href="{{url_for('static',filename='css/bootstrap.min.css')}}">
    <style>
    .button{
        background-color: white;
        color: black;
        border: 2px solid #4CAF50;
    }

    .button:hover {
        background-color: #4CAF50;
        color: white;
    }

    .button[disabled] {
        opacity: 0.6;
        cursor: not-allowed;
    }

    </style>
    <title>客户管理</title>
</head>
<body>


<div id="client_manage" style="margin:auto; width:95%">


    <h3>客户管理</h3>
    <div>
        <div style="display:inline-block;">
           <button type="button" class="btn btn-success" onclick="addClient()">添加客户</button>
        </div>
        <div  id = "submit" style="position:absolute;left:50%;display:inline-block;">
           <button type="button" class="btn btn-success" onclick="cancel()">取消添加</button>
        </div>
    </div>

    <br/>
    <br/>
    <div style="margin:auto">

    <div id="clientManageDataTable" class="table table-striped table-bordered" cellspacing="0" width="95%">
    </div>
    </div>

</div>


<script>
        function formatDate(time){
            var date = new Date(time);

            var year = date.getFullYear(),
                month = date.getMonth()+1,//月份是从0开始的
                day = date.getDate(),
                hour = date.getHours(),
                min = date.getMinutes(),
                sec = date.getSeconds();
            var newTime = year + '-' +
                        (month < 10? '0' + month : month) + '-' +
                        (day < 10? '0' + day : day) + ' ' +
                        (hour < 10? '0' + hour : hour) + ':' +
                        (min < 10? '0' + min : min) + ':' +
                        (sec < 10? '0' + sec : sec);

            return newTime;
        }

        function addDate(date,days){
            var d=new Date(date);
            d.setDate(d.getDate()+days);
            var m=d.getMonth()+1;
            return d.getFullYear()+'-'+m+'-'+d.getDate();
        }

        function addClient() {
            var inputList = $(".no-editor");
            if (inputList.length>0){
                return;
            }
            var go = window.confirm("您确定要添加客户吗?")
            if (go == false){
                return;
            }
            window.alert("资产和收益会第二天自动刷新，请填写其他!");
            var tdList = $("#clientManageDataTable").find('table > tbody > tr >td');
            var widthList = [];

            tdList.each(function(key,value){
                var value = $(value).width();
                widthList.push(value);
            });
            var trList = $("#clientManageDataTable").find('table > tbody > tr');
            var trLength = String(trList.length+1);


            var rowStr = jQuery('<tr></tr>');
            var indexHtml = jQuery('<td>' + trLength + '</td>');
            rowStr.append(indexHtml);

            var accountIdWidth = widthList[1];
            var accountIdHtml = jQuery('<td>' +'<input type="text" style="width:'+String(accountIdWidth)+'px;" ' +
                'class="account-id"/>' + '</td>');
            rowStr.append(accountIdHtml);

            var userNameWidth = widthList[2];
            var userNameHtml = jQuery('<td>' +'<input type="text" style="width:'+String(userNameWidth)+'px;" ' +
                'class="user-name"/>' + '</td>');
            rowStr.append(userNameHtml);

            var passwordWidth = widthList[3];
            var passwordHtml = jQuery('<td>' +'<input type="text" style="width:'+String(passwordWidth)+'px;" ' +
                'class="password"/>' + '</td>');
            rowStr.append(passwordHtml);

            var initCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(initCapitalHtml);

            var useCycleWidth = widthList[5];
            var useCycleHtml = '<select class="no-editor" onclick="noEditor()" style="width:'+String(useCycleWidth)+'px;" disabled="disabled">' +
                        '<option value="noOpen">未开通用户</option>' +
                        '<option value="try">试用用户</option>' +
                        '<option value="month">月用户</option>' +
                        '<option value="year">年用户</option>' +
                        '</select>';
            useCycleHtml = jQuery('<td onclick="noEditor()">'+useCycleHtml+'</td>');
            rowStr.append(useCycleHtml);

            var totalCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(totalCapitalHtml);
            var usableCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(usableCapitalHtml);
            var freezeCapitalHtml = jQuery('<td>0</td>');
            rowStr.append(freezeCapitalHtml);
            var profitHtml = jQuery('<td>0</td>');
            rowStr.append(profitHtml);

            var today = formatDate(new Date().getTime()).substring(0,11);
            var endDate = formatDate(addDate(today,30)).substring(0,11);
            var alertDate = formatDate(addDate(endDate,-10)).substring(0,11);

            var beginDateWidth = widthList[10];
            var beginDateHtml = jQuery('<td onclick="noEditor()">' +'<input type="text" style="width:'+String(beginDateWidth)+'px;" ' +
                'class="no-ediotr" value="'+today+'" disabled=true/>' + '</td>');
            rowStr.append(beginDateHtml);

            var endDateWidth = widthList[11];
            var endDateHtml = jQuery('<td onclick="noEditor()">' +'<input type="text" style="width:'+String(endDateWidth)+'px;" ' +
                'class="no-editor" value="'+endDate+'" disabled=true/>' + '</td>');
            rowStr.append(endDateHtml);

            var alertDateWidth = widthList[12];
            var alertDateHtml = jQuery('<td onclick="noEditor()">' +'<input type="text" style="width:'+String(alertDateWidth)+'px;" ' +
                'class="no-editor" value="'+alertDate+'" disabled=true/>' + '</td>');
            rowStr.append(alertDateHtml);

            var operateTimesHtml = jQuery('<td>0</td>');
            rowStr.append(operateTimesHtml);

            var brokerNameWidth = widthList[14];
            var brokerNameHtml = jQuery('<td>' +'<input type="text" style="width:'+String(brokerNameWidth)+'px;" ' +
                'class="broker-name"/>' + '</td>');
            rowStr.append(brokerNameHtml);

            var strategyWidth = widthList[15];
            var strategyHtml = '<label><input class="no-ediotr"  type="checkbox" ' +
                'disabled=true value="" >robot2 </label><br/>';
            strategyHtml = jQuery('<td onclick="noEditor()">' + strategyHtml + '</td>');
            rowStr.append(strategyHtml);

            var cashWidth = 100;
            var cashHtml = jQuery('<td onclick="noEditor()">' +'<input type="text" style="width:'+String(cashWidth)+'px;" ' +
                'class="no-editor" value="1" disabled=true/>' + '</td>');
            rowStr.append(cashHtml);

            var buttonWidth = widthList[17];
            var buttonHtml = jQuery('<td><button class="button" type="text" onclick="submit()" >提交</button></td>');
            rowStr.append(buttonHtml);

            $("#clientManageDataTable").find('table > tbody').append(rowStr);
            $("#submit").show();

        }
        function noEditor() {

            window.alert("请先提交后再进行配置!");
        }
        function changeType(accountId) {
            var useType = $("."+accountId).find("option:selected").text();
            var today = formatDate(new Date().getTime()).substring(0, 11);
            var tomorrow = formatDate(addDate(today, 1)).substring(0, 11);
            var oneMonthAfter = formatDate(addDate(today, 30)).substring(0, 11);
            var oneMonthAfterAlert = formatDate(addDate(oneMonthAfter, -10)).substring(0, 11);
            var oneYearAfter = formatDate(addDate(today, 365)).substring(0, 11);
            var oneYearAfterAlert = formatDate(addDate(oneYearAfter, -10)).substring(0, 11);
            if (useType=='未开通用户'|useType=='月用户'|useType=='试用用户'){
                $("."+accountId+".beginDate").val(tomorrow);
                $("."+accountId+".alertDate").val(oneMonthAfterAlert);
                $("."+accountId+".endDate").val(oneMonthAfter);
            }
            if (useType=='年用户'){
                $("."+accountId+".beginDate").val(tomorrow);
                $("."+accountId+".alertDate").val(oneYearAfterAlert);
                $("."+accountId+".endDate").val(oneYearAfter);
            }


        }


        function editorAccount(accountId) {
            var buttonList = $(".button");
            var hasEditoring = false;
            buttonList.each(function (key, value) {
                if ($(value).prop("disabled") == true) {
                    hasEditoring = true;
                    var className = $(value).attr('class').split(' ')[1];
                    window.alert("请先完成对" + className + "的编辑!");
                    return false;
                }

            });
            if (hasEditoring == true) {
                return;
            }
            var accountId = accountId;
            $(".editor." + accountId).removeAttr("disabled");
            $(".button." + accountId).attr("disabled", "true");
            $("#editor_to_show").show();
            var htmlStr = '<div align="center" id = "editor_to_show" >\n' +
                '\n' +
                '    <div class="btn-group btn-group-lg" role="group" aria-label="...">\n' +
                '\n' +
                '        <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-success" onclick="delAccount(\'' + accountId +
                '\')">删除该客户</button>\n' +
                '        </div>\n' +
                '\n' +
                '        <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-success" onclick="editorSubmit(\'' + accountId +
                '\')">提交</button>\n' +
                '        </div>\n' +
                '\n' +
                '\n' +
                '        <div class="btn-group" role="group">\n' +
                '        <button type="button" class="btn btn-success" onclick="cancel()">取消</button>\n' +
                '        </div>\n' +
                '        \n' +
                '\n' +
                '    </div>\n' +
                '</div>';
            $("#client_manage").append(htmlStr);
        }

        function selectStrategy(accountId) {

            if ($("." + accountId + "[type='checkbox']").is(':checked')) {
                window.alert("你已经为客户 " + accountId + " 添加绑定关系吗!");
            } else {
                window.alert("你已经为客户 " + accountId + " 解除绑定关系!");
            }

        }

        function delAccount(accountId) {
            var go = window.confirm("你确定要删除客户" + accountId + "吗？");
            if (go == false) {
                return;
            }
            $.ajax({
                url: "/delClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({'account_id': accountId}),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    refreshData();
                    location.reload();
                }
            });
        }

        function editorSubmit(accountId) {
            var alertStr = "配置如下:\n用户类型:";
            var useType = $("." + accountId).find("option:selected").text();
            alertStr += String(useType) + "\n";
            var openStrategy = 0;
            if ($("." + accountId + "[type='checkbox']").is(':checked')) {
                openStrategy = 1;
                alertStr += "策略:robot2\n";
                if (useType == '未开通用户') {
                    window.alert("请选择使用周期!");
                    return;
                }
            } else {

                openStrategy = 0;
                alertStr += "策略:未绑定策略\n";
            }
            var cash = $("." + accountId + ".cash").val();
            alertStr += "出手资金:" + cash + "元,小于1手按1手算\n";
            var go = window.confirm(alertStr);
            if (go == false) {
                return;
            }
            var beginDate = $(".beginDate." + accountId).val();
            var alertDate = $(".alertDate." + accountId).val();
            var endDate = $(".endDate." + accountId).val();
            $.ajax({
                url: "/editorClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({
                    'account_id': accountId, 'use_type': useType, 'open_strategy': openStrategy, 'cash': cash,
                    'begin_date': beginDate, 'alert_date': alertDate, 'end_date': endDate
                }),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    refreshData();
                    location.reload();
                }
            });
        }

        function cancel() {
            location.reload();
        }

        function submit() {
            var accountId = $(".account-id").val();
            if (accountId == '') {
                window.alert("账户id不能为空!");
                return;
            }
            var userName = $(".user-name").val();
            if (userName == '') {
                window.alert("用户名不能为空!");
                return;
            }
            var password = $(".password").val();
            if (password == '') {
                window.alert("密码不能为空!");
                return;
            }

            var brokerName = $(".broker-name").val();
            if (brokerName == '') {
                window.alert("券商名不能为空!");
                return;
            }

            var qsid = '';
            var brokerNameList = [];
            for (var i=0;i<brokerNameData.length;i++){
                brokerNameList.push(brokerNameData[i]['brokerName']);
            }
            if (brokerNameList.indexOf(brokerName)>-1){
                var index = brokerNameList.indexOf(brokerName);
                qsid = brokerNameData[index]['qsid'];
            }else if(brokerNameList.indexOf(brokerName.replace('证券',''))>-1){
                var index = brokerNameList.indexOf(brokerName.replace('证券',''));
                brokerName = brokerNameData[index]['brokerName'];
                qsid = brokerNameData[index]['qsid'];
            }else{
                window.alert("券商名称输入有误!");
                return;
            }

            var go = window.confirm("你确定要添加客户" + accountId + "吗？");
            if (go == false) {
                return;
            }
            if (accountList.indexOf(accountId) > -1){
                window.alert("该账户已经存在!")
                return;
            }

            var alertStr = "请仔细核对，添加后不允许更改:\n";

            alertStr += "账户id: " + accountId + "\n";
            alertStr += "用户名: " + userName + "\n";
            alertStr += "密码: " + password + "\n";
            alertStr += "券商名称: " + brokerName + "\n";

            var go = window.confirm(alertStr);
            if (go == false) {
                return;
            }
            $.ajax({
                url: "/addClient",
                async: true,
                type: 'POST',
                data: JSON.stringify({'account_id': accountId, 'user_name': userName,'password':password, 'broker_name': brokerName,'qsid':qsid}),
                dataType: 'json',
                success: function (result) {
                    var message = result.message;
                    alert(message);
                    $("#submit").hide();
                    refreshData();
                }
            });

        }

        $("#submit").hide();
        var clientManageDataTable = null;
        var accountList = [];
        var brokerNameData = [];
        $.getJSON("/static/json/brokerName.json", function (data){
            brokerNameData = data;

      //显示处理后的数据
    });

        clientManageDataTable = jQuery("#clientManageDataTable").raytable({
            datasource: {data: [], keyfield: 'stock_code'},
            columns: [
                {field: "accountId", title: "账户"},
                {field: "userName", title: "用户名"},
                {field:"password",title:"密码"},
                {field: "initCash", title: "本金"},
                {field: "useCycle", title: "使用周期"},
                {field: "nowCash", title: "总资产"},
                {field: "usableCash", title: "可用资金"},
                {field: "marketValue", title: "市值"},
                {field: "profit", title: "收益(%)"},
                {#{ field: "renew", title: "续费"},#}
                {field: "beginDate", title: "开通日期"},
                {field: "endDate", title: "截止日期"},
                {field: "alertDate", title: "提醒续费日期"},
                {field: "operateTimes", title: "操作次数"},
                {field: "brokerName", title: "券商名称"},
                {field: "strategy", title: "策略"},
                {#{field:"status",title:"账户状态"},#}
                {field: "amount", title: "出手资金(元,最少按1手)"},
                {field: "editor", title: "编辑"}
            ],
            pagesize: 20,
            maxPageButtons: 5,
            rowNumbers: true
        });

        function refreshData() {
            $.ajax({
                url: "/clientManageData?account=001",
                async: true,
                success: function (result) {
                    var obj = JSON.parse(result);
                    var clientList = obj.clientList;
                    for (i=0;i<clientList.length;i++){
                        accountList.push(clientList[i]['accountId']);
                    }

                    clientManageDataTable.data(clientList, 'stock_code');
                }
            })
        }

            refreshData();


</script>

</body>
</html>